package io.demo_8_threadlocal;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Random;

public class A implements Runnable{
    ThreadLocal<BufferedReader> m=new ThreadLocal();
    Random r=new Random();
    @Override
    public void run() {
        String name= Thread.currentThread().getName();
        System.out.println(name+"开始读取小说。。。。");
        String s;
        int num=1;
        BufferedReader br=getReader();
        try {
            while ((s=br.readLine())!=null){
                System.out.println(name+"读取："+(num++)+s);
                Thread.sleep(r.nextInt(5000));
            }
            m.get().close();
        } catch (Exception e) {}
        //删除线程的本地变量
        m.remove();

    }

    BufferedReader getReader(){
        //获取线程本地变量
        BufferedReader br=m.get();
        if(br==null){
            try {
                br=new BufferedReader(new FileReader("d:/1.txt"));
                //保存线程本地变量
                m.set(br);
            } catch (FileNotFoundException e) {}
        }
        return br;
    }
}
